package alex.edu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

@SuppressWarnings("unchecked")
public class MyItemizedOverlay extends ItemizedOverlay {

	private List<OverlayItem> items;
	private Drawable marker;
	MapActivity mapAct;
	Button textView;

	public MyItemizedOverlay(Drawable defaultMarker, MapActivity mapActivity) {
		super(defaultMarker);
		items = new ArrayList();
		mapAct = mapActivity;
		marker = defaultMarker;
	}

	@Override
	protected OverlayItem createItem(int index) {
		return items.get(index);
	}

	@Override
	public int size() {
		return items.size();
	}

	@Override
	public boolean onTap(GeoPoint p, MapView mapView) {
		MapView.LayoutParams geoLP;
		geoLP = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,
				MapView.LayoutParams.WRAP_CONTENT, p,
				MapView.LayoutParams.TOP_LEFT);
		textView = new Button(mapAct.getApplicationContext());
		mapView.addView(textView, geoLP);

		textView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textView.setVisibility(textView.INVISIBLE);
				textView.setBackgroundColor(Color.BLUE);
			}
		});

		Geocoder gc = new Geocoder(mapAct, Locale.getDefault());
		List<Address> addresses = null;
		try {
			addresses = gc.getFromLocation(p.getLatitudeE6() / 1e6, p
					.getLongitudeE6() / 1e6, 1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// get country name
		String countryName = addresses.get(0).getCountryName();
		ServerResponse serverResponse = new ServerResponse();
		serverResponse.getAllStatus(mapAct.getString(R.string.country_user)
				+ "?country=" + countryName);
		for (int i = 0; serverResponse.countries_user.size() > 0
				&& i < serverResponse.countries_user.get(0).users.size(); i++) {
			// add user status in this country to the edit box
			textView.append(serverResponse.countries_user.get(0).users.get(i)
					.toString());
		}
		return super.onTap(p, mapView);
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		super.draw(canvas, mapView, shadow);
		boundCenterBottom(marker);

	}

	public void addItem(OverlayItem item) {
		items.add(item);
		populate();
	}
}